// xmls
var songxml;
var artistxml;
var albumxml;
var playlistxml;
// results
var songrs;
var artistrs;
var albumrs;
var playlistrs;
// general
var searchBox;
var searchBoxDiv;
var resultBox;
var query;
var searchBoxId;
var contextPath;

function ExecuteSearch(event,context){
    searchBox = document.getElementById('search_input');
    resultBox = document.getElementById('search_result');
    query = searchBox.value;
    searchBoxDiv = searchBox.parentNode;
    contextPath = context;
    
    // parse 4 xmls to doms
    xml = localStorage.getItem("songxml");
    songxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("artistxml");
    artistxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("albumxml");
    albumxml = new DOMParser().parseFromString(xml,"text/xml");
    xml = localStorage.getItem("playlistxml");
    playlistxml = new DOMParser().parseFromString(xml,"text/xml");

    OnKeyUpProcess(event);
}

function OnKeyUpProcess(e){
    var keynum;
    if(window.event)
        keynum = e.keyCode;  // code for IE6, IE5
    else
    if(e.which)
        keynum = e.which;  // code for IE7+, Firefox, Chrome, Opera, Safari

    if(keynum==13){ // check if enter button
        ClearResult();
    }else{
        if (searchBox.value.length == 0) {
            ClearResult();
        }
        if (searchBox.value.length < 1)
            return;
        InstantSearch();
    }
}

function InstantSearch(){

    // var str = searchBox.value.trim().toUpperCase().VNize().removeAccent();
    var str = searchBox.value.trim().VNize().removeAccent().toUpperCase();

    SearchInSong(str);
    SearchInArtist(str);
    SearchInAlbum(str);
    SearchInPlaylist(str);

    OnProgress();
    ShowResult();
}

function SearchInSong(str){
    var songs = songxml.getElementsByTagName("Song"); // <Song>
    songrs = [];

    for(i=0;i<songs.length;i++){
        // Title
        var title = songs[i].getElementsByTagName("SongTitle")[0].firstChild.nodeValue;
        var comparison = title.VNize().removeAccent().toUpperCase();

        if(comparison.indexOf(str)>-1){

            var id = songs[i].getElementsByTagName("SongID")[0].firstChild.nodeValue;
            var isMV = songs[i].getElementsByTagName("isMV")[0].firstChild.nodeValue;
            var src = songs[i].getElementsByTagName("SongSRC")[0].firstChild.nodeValue;
            // Artist
            var artists = songs[i].getElementsByTagName("Artist");
            var artist = [];
            var artistList = [];
            for(j=0;j<artists.length;j++){
                var artistId = artists[j].getElementsByTagName("ArtistID")[0].firstChild.nodeValue;
                var artistName = artists[j].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;

                artist.push({
                    artistId:artistId,
                    artistName:artistName
                });

                artistList.push({
                    artist:artist
                });
            }
            // add result
            songrs.push({
                id:id,
                isMV:isMV,
                title:title,
                src:src,
                artistList:artistList
            });
        } // end comparison
    }
}

function SearchInArtist(str){
    var artists = artistxml.getElementsByTagName("Artist"); // <Song>
    artistrs = [];

    for(i=0;i<artists.length;i++){
        // Title
        var name = artists[i].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
        // var comparison = name.toUpperCase().VNize().removeAccent();
        var comparison = name.VNize().removeAccent().toUpperCase();

        if(comparison.indexOf(str)>-1){
            var id = artists[i].getAttribute("ArtistID");
            var src = artists[i].getElementsByTagName("ArtistImageSRC")[0].firstChild;
            if(src!=null){
                src = artists[i].getElementsByTagName("ArtistImageSRC")[0].firstChild.nodeValue;
            }else{
                src = "ArtistDefault.jpg"; // set default image src
            }

            artistrs.push({
                id:id,
                name:name,
                src:src
            });
        } // end comparison
    }
    
}

function SearchInAlbum(str){
    var albums = albumxml.getElementsByTagName("Album"); // <Song>
    albumrs = [];

    for(i=0;i<albums.length;i++){
        // Title
        var title = albums[i].getElementsByTagName("AlbumTitle")[0].firstChild.nodeValue;
        // var comparison = name.toUpperCase().VNize().removeAccent();
        var comparison = title.VNize().removeAccent().toUpperCase();

        if(comparison.indexOf(str)>-1){
            var songList = [];
            var id = albums[i].getElementsByTagName("AlbumID")[0].firstChild.nodeValue;
            var src = albums[i].getElementsByTagName("AlbumCoverSRC")[0].firstChild.nodeValue;
            var artistName = albums[i].getElementsByTagName("ArtistName")[0].firstChild.nodeValue;
            albumrs.push({
                id:id,
                artistName:artistName,
                src:src,
                title:title,
                songs:songList
            });
        } // end comparison
    }
    
}

function SearchInPlaylist(str){
    playlistrs = [];
}

function ShowResult(){
    // Clear
    ClearResult();

    var output = "";

    if(artistrs.length!=0 || songrs.length!=0
        || albumrs.length!=0 || playlistrs.length!=0){
        output += "<ul class='search_box'>";
        output += ShowBrief();
        output += ShowResultForArtist();
        output += ShowResultForAlbum();
        output += ShowResultForMV();
        output += ShowResultForSong();
        output +="</ul>"
    }else{
        output += "<ul class='search_box'>";
        output += ShowBrief();
        output += "</ul>";
    }
    
    searchBoxDiv.innerHTML += output;
    Focus();
}

function ShowResultForSong(){
    var output="";
    var out="";
    songrs = sortByViews(songrs);
    if(songrs.length==0){
        return output;
    }
    if(songrs.length>=3){
        n=3;
    }else{
        n=songrs.length;
    }
    for(var i=0;i<n;i++){
        if(songrs[i].isMV =="false"){
            out += "<li class='search_item'>";
            out += "<a class='song_item' href='musicplayer.jsp?id="+songrs[i].id+"&type=1'>"
            out += "<p>"+songrs[i].title+"</p>" + "<br/>";
            var artistList = songrs[i].artistList;
            for(var j=0;j<artistList.length;j++){
                out += "<p class='artist'>"+artistList[0].artist[j].artistName+"</p>";
                if(j!=artistList.length-1){
                    out += ", ";
                }
            }
            out += "</a></li>";
        }
    }
    if(out!=""){
        output+="<li class='result_container'>";
        output+="<h3>Bài hát</h3>";
        output+="<ul class='search_content'>";
        output+= out;
        output+="</ul>";
        output+="</li>";
    }

    

    return output;
}

function ShowResultForMV(){
    var output="";
    var out = "";
    var mvlist = getMVList(songrs);
    mvlist = sortByViews(mvlist);
    if(mvlist.length==0){
        return output;
    }
    if(mvlist.length>=3){
        n=3;
    }else{
        n=mvlist.length;
    }
    
    for(var i=0;i<n;i++){
        if(mvlist[i].isMV =="true"){
            output += "<li class='search_item'>";
            output += "<a href='musicplayer.jsp?id="+mvlist[i].id+"&type=4'>"
            output += "<img src='"+contextPath + "/db/" +
            mvlist[i].artistList[0].artist[0].artistName.removeDotCharacter() + "/MV/" + mvlist[i].src + ".jpg"+"'/>";
            output += "<p>"+mvlist[i].title+"</p>" + "<br/>";
            var artistList = mvlist[i].artistList;
            for(var j=0;j<artistList.length;j++){
                output += "<p class='artist'>"+artistList[0].artist[j].artistName+"</p>";
                if(j!=artistList.length-1){
                    output += ", ";
                }
            }
            output += "</a></li>";
        } // end check
    }
    if(output!=""){
        out +="<li class='result_container'>";
        out +="<h3>Video Clip</h3>";
        out +="<ul class='search_content'>";
        out += output;
        out +="</ul>";
        out +="</li>";
    }
    return out;
}

function ShowResultForArtist(){
    var output="";
    artistrs = sortByViews(artistrs);
    if(artistrs.length==0){
        return output="";
    }

    if(artistrs.length>=3){
        n = 3;
    }else{
        n = artistrs.length;
    }
    output+="<li class='result_container'>";
    output+="<h3>Nghệ sỹ</h3>";
    output+="<ul class='search_content'>";
    for(var i=0;i<n;i++){
        var imgsrc = contextPath + "/db/" + artistrs[i].name.removeDotCharacter() +"/"+ artistrs[i].src;
        // output
        output += "<li class='search_item'>";
        output += "<a href='artist.jsp?ArtistID="+artistrs[i].id+"'>";
        output += "<img class='search_image' src='"+imgsrc+"'/>";
        output += "<p>" + artistrs[i].name;
        output += "</p></a>"
        output += "</li>";
        
    }
    output+="</ul></li>";
    return output;
}

function ShowResultForAlbum(){
    var output="";

    albumrs = sortByViews(albumrs);
    if(albumrs.length==0){
        return output="";
    }
    if(albumrs.length>=3){
        n = 3;
    }else{
        n = albumrs.length;
    }

    output+="<li class='result_container'>";
    output+="<h3>Album</h3>";
    output+="<ul class='search_content'>";
    for(var i=0;i<n;i++){
        var imgsrc = contextPath + "/db/" + albumrs[i].artistName.removeDotCharacter()
        +"/Album/"+albumrs[i].title.removeDotCharacter()+"/"+albumrs[i].src;
        // output
        
        output += "<li class='search_item'>";
        output += "<a href='musicplayer.jsp?id="+albumrs[i].id+"&type=2'>";
        output += "<img class='search_image' src='"+imgsrc+"'/>";
        output += "<p>"+albumrs[i].title+"</p>"
        output += "</br>";
        output+= "<p>"+albumrs[i].artistName+"</p>";
        output += "</a>"
        output += "</li>";
        
    }
    output+="</ul></li>";
    return output;
}

function ShowBrief(){
    var output = "";

    output += "<h4>Có "+(artistrs.length + albumrs.length + songrs.length + playlistrs.length)+
    " kết quả cho từ khóa: <i>"+query+"</i></h4>";

    return output;
}

function OnProgress(){
    // Clear
    ClearResult();

    var output = "";
    output += "<ul class='search_box'>";
    output += "<li class='search_progress'>" + "Search...";
    output += "</li></ul>";

    searchBoxDiv.innerHTML += output;
    Focus();
}

function ClearResult(){
    window.name="";
    var myUl = searchBoxDiv.getElementsByTagName("UL");
    for(var i=0;i<myUl.length;i++){
        searchBoxDiv.removeChild(myUl[i]);
    }
}

function Focus(){
    document.getElementById('search_input').focus();
    document.getElementById('search_input').value = query;
}

function getMVList(des){
    var list = [];
    for(var i=0;i<des.length;i++){
        if(des[i].isMV == "true"){
            list.push(des[i]);
        }
    } // end for
    return list;
}